<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { getTempHistory } from "@/api/system/realtime";
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    // chartData: {
    //   type: Object,
    //   required: true
    // }
  },
  data() {
    return {
      chart: null,
      ws: null,
      chartData: {
        times: [],  // 时间轴数据
        temperatureExpecteds: [],  // 数值数据
        temperatureActuals: [],
        humiditys: [],
        soilMoistures: []
      },
      maxDataPoints: 20  // 最大显示数据点数
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  // created() {
  //     this.getTempData();
  //   },
  mounted() {
    // this.$nextTick(() => {
      this.initChart();
      this.initWebSocket();
    // })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initWebSocket() {
      // 创建WebSocket连接
      const wsUrl = 'ws://127.0.0.1:8080/traffic'; // 替换为你的WebSocket地址
      this.ws = new WebSocket(wsUrl);
      
      this.ws.onopen = () => {
        console.log('WebSocket连接已建立');
        // 可以在这里发送初始请求（如果需要）
        // this.ws.send(JSON.stringify({action: 'subscribe'}));
      };
      
      this.ws.onmessage = event => {
        // 处理接收到的数据
        const newData = JSON.parse(event.data);
        console.log(newData);
        this.updateChartData(newData);
      };
      
      this.ws.onerror = error => {
        console.error('WebSocket错误:', error);
      };
      
      this.ws.onclose = () => {
        console.log('WebSocket连接已关闭');
        // 可以尝试重新连接
        setTimeout(() => {
          this.initWebSocket();
        }, 5000);
      };
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ times, temperatureExpecteds, temperatureActuals, humiditys, soilMoistures} = {}) {
      this.chart.setOption({
        xAxis: {
          type: "category",
          data: times,
          boundaryGap: false,
          axisTick: {
            show: false
          }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        legend: {
          data: ['期望温度', '实际温度', '相对湿度', '土壤湿度']
        },
        series: [{
          name: '期望温度', itemStyle: {
            normal: {
              color: '#FF005A',
              lineStyle: {
                color: '#FF005A',
                width: 2
              }
            }
          },
          smooth: true,
          type: 'line',
          data: temperatureExpecteds,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        },
        {
          name: '实际温度',
          smooth: true,
          type: 'line',
          itemStyle: {
            normal: {
              color: '#3888fa',
              lineStyle: {
                color: '#3888fa',
                width: 2
              },
              areaStyle: {
                color: '#f3f8ff'
              }
            }
          },
          data: temperatureActuals,
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        },
        {
          name: '相对湿度',
          smooth: true,
          type: 'line',
          itemStyle: {
            normal: {
              color: '#EF88BE',
              lineStyle: {
                color: '#EF88BE',
                width: 2
              },
              areaStyle: {
                color: '#f3f8ff'
              }
            }
          },
          data: humiditys,
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        },
        {
          name: '土壤湿度',
          smooth: true,
          type: 'line',
          itemStyle: {
            normal: {
              color: '#732BF5',
              lineStyle: {
                color: '#732BF5',
                width: 2
              },
              areaStyle: {
                color: '#f3f8ff'
              }
            }
          },
          data: soilMoistures,
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        }]
      })
    },
    updateChartData(newDataPoint) {
      // 添加新数据点
      this.chartData.times.push(newDataPoint.currentTime);
      this.chartData.temperatureActuals.push(newDataPoint.temperatureActual); // 假设数据格式为 { value: 123 }
      this.chartData.temperatureExpecteds.push(newDataPoint.temperatureExpected);
      this.chartData.humiditys.push(newDataPoint.humidity);
      this.chartData.soilMoistures.push(newDataPoint.soilMoisture);
      // 限制数据点数量
      if (this.chartData.times.length > this.maxDataPoints) {
        this.chartData.times.shift();
        this.chartData.temperatureActuals.shift();
        this.chartData.temperatureExpecteds.shift();
        this.chartData.humiditys.shift();
        this.chartData.soilMoistures.shift();
      }
      
      // 准备ECharts数据格式
      const seriesData = this.chartData.times.map((time, index) => {
        return [time, this.chartData.temperatureActuals[index]];
      });
      console.log(seriesData)
      console.log(this.chartData.times)
      console.log(this.chartData.temperatureExpecteds)
      console.log(this.chartData.temperatureActuals)
      // 更新图表

      this.setOptions(this.chartData.times, this.chartData.temperatureExpecteds, this.chartData.temperatureActuals, this.chartData.humiditys, this.chartData.soilMoistures);
    },
  }
}
</script>
